package com.hahaliu.hahaliu.controller.admin;

import com.hahaliu.hahaliu.common.result.Result;
import com.hahaliu.hahaliu.common.utils.JwtUtil;
import com.hahaliu.hahaliu.common.context.CurrentUser;
import com.hahaliu.hahaliu.pojo.dto.UserLoginDTO;
import com.hahaliu.hahaliu.pojo.entity.User;
import com.hahaliu.hahaliu.pojo.vo.UserLoginVO;
import com.hahaliu.hahaliu.service.user.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/admin/user")
@Api(tags = "管理端用户相关接口")
@Slf4j
public class AdminController {
	@Autowired
	private UserService userService;
	@Autowired
	private JwtUtil jwtUtil;
	@Autowired
	private CurrentUser currentUser;

	@PostMapping("/login")
	@ApiOperation("管理员登录")
	public Result<UserLoginVO> login(@RequestBody UserLoginDTO userLoginDTO) {
		log.info("管理员登录：{}", userLoginDTO);

		User user = userService.adminLogin(userLoginDTO);

		//将uid封装成一个jwttoken，同时token也会被缓存到redis中
		String token = jwtUtil.createToken(user.getUId().toString(), "admin");

		UserLoginVO userLoginVO = UserLoginVO.builder()
				.user(user)
				.token(token)
				.build();

		return Result.success(userLoginVO);
	}

	@GetMapping("/personal/info")
	@ApiOperation(value = "查询当前用户信息")
	public Result<User> getPersonal() {
		Integer uId = currentUser.getUserId();

		User user = userService.getById(uId);

		return Result.success(user);
	}
}
